package com.yangkunhong.utils;

import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponse;
import com.google.gson.Gson;
import com.yangkunhong.config.AliSmsConfig;
import darabonba.core.client.ClientOverrideConfiguration;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * ClassName: AliSms
 * Description:
 *
 * @author yangkunhong
 * @date 2024/6/25 8:36
 */
public class AliSmsUtil {
    private static  String ACCESS_KEY = "XXXXXXX";
    private static  String SECRET =     "XXXXXXXXX";
    private static  String signName = "ABC商城";
    private static  String templateCode = "XXXXXXX";
    static {
        System.out.println("INIT");
        AliSmsConfig config = ConfigUtil.getConfig(AliSmsConfig.class);
        ACCESS_KEY = config.getAccessKey();
        SECRET = config.getSecret();
        signName = config.getSignName();
        templateCode = config.getTemplateCode();


    }
    public static boolean sendSms(String phone, String code) {
        // Configure Credentials authentication information, including ak, secret, token

        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                // Please ensure that the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET are set.
                .accessKeyId(ACCESS_KEY)
                .accessKeySecret(SECRET)
                //.securityToken(System.getenv("ALIBABA_CLOUD_SECURITY_TOKEN")) // use STS token
                .build());

        // Configure the Client
        AsyncClient client = AsyncClient.builder()
                //.httpClient(httpClient) // Use the configured HttpClient, otherwise use the default HttpClient (Apache HttpClient)
                .credentialsProvider(provider)
                //.serviceConfiguration(Configuration.create()) // Service-level configuration
                // Client-level configuration rewrite, can set Endpoint, Http request parameters, etc.
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                // Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
                                .setEndpointOverride("dysmsapi.aliyuncs.com")
                        //.setConnectTimeout(Duration.ofSeconds(30))
                )
                .build();
        // Parameter settings for API request
        SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                .phoneNumbers(phone)
                .templateCode(templateCode)
                .templateParam("{code:"+code+"}")
                .signName(signName)
                // Request-level configuration rewrite, can set Http request parameters, etc.
                // .requestConfiguration(RequestConfiguration.create().setHttpHeaders(new HttpHeaders()))
                .build();

        // Asynchronously get the return value of the API request
        CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);
        // Synchronously get the return value of the API request
        SendSmsResponse resp = null;
        try {
            resp = response.get();
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
        //System.out.println(new Gson().toJson(resp));
        // Asynchronous processing of return values

        response.thenAccept(response01 -> {
            System.out.println(new Gson().toJson(response01));
            System.out.println("response01.getBody().getCode()"+response01.getBody().getCode());
        }).exceptionally(throwable -> {
            // Handling exceptions

            System.out.println(throwable.getMessage());
            return null;
        });

        // Finally, close the client
        client.close();
        return true;
    }
}
